package cors

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

// Cors 解决跨域中间件
func Cors(ctx *gin.Context) {
	ctx.Writer.Header().Add("Access-Control-Allow-Origin", "*")
	ctx.Writer.Header().Add("Access-Control-Max-Age", strconv.Itoa(86400))
	ctx.Writer.Header().Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS")
	ctx.Writer.Header().Add("Access-Control-Expose-Headers", "Content-Length")
	ctx.Writer.Header().Add("Access-Control-Allow-Headers", "*")
	ctx.Writer.Header().Add("Access-Control-Allow-Credentials", "true")

	if ctx.Request.Method == "OPTIONS" {
		ctx.AbortWithStatus(http.StatusNoContent)
		return
	}
	ctx.Request.Header.Del("Origin")
	ctx.Next()
}
